﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace SentientGrid
{
    public class JsonBuilder<T>
    {
        private IEnumerable<T> _data;
        private AttributeParser _attributeParser;
        private GridState _state;

        public object BuildJsonObject()
        {

            var props = _attributeParser.GetDisplayedProperties();
            var rows = new List<object>();
            foreach (var i in _data)
            {
                var cols = new List<object>();

                foreach (var j in props)
                {
                    var val = j.GetValue(i, null);
                    if (val == null)
                    {
                        val = string.Empty;
                    }
                    cols.Add(val.ToString());
                }

                var row = new
                {

                    id = (_attributeParser.GetPrimaryKeyProperty() != null ? _attributeParser.GetPrimaryKeyProperty().GetValue(i, null) : string.Empty),
                    cell = cols.ToArray()
                };

                rows.Add(row);

            }

            // JSON Object
            return new
            {
                root = "rows",
                total = _state != null ? _state.Total : 1,
                records = rows.Count(),
                rows = rows.ToArray()
            };
        }

        public JsonBuilder(IEnumerable<T> mData)
        {
            _data = mData;
            _attributeParser = new AttributeParser(_data.GetType().GetGenericArguments()[0]);
        }

        public void FormatToGrid(GridState state)
        {
            
            var qry = _data.AsQueryable()
                .Skip(state.Rows * (state.Page - 1))
                .Take(state.Rows);
            if (!string.IsNullOrEmpty(state.Sidx))
                qry.OrderBy(string.Format("{0} {1}", state.Sidx, state.Sord));


            state.Total = _data.Count() / state.Rows;
            if (_data.Count() % state.Rows > 0) state.Total++;
            _data = qry.ToList();
            _state = state;

            
        }
    }
}
